package com.symria.framework.util;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Enumeration;

import javax.servlet.ServletContext;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import org.apache.struts2.ServletActionContext;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.symria.role.util.Logger;


public class HttpHelp {
	private final static Logger log = Logger.getLogger(HttpHelp.class);
	public final static String IP1 = "x-forwarded-for";
	public final static String IP2 = "Proxy-Client-IP";
	public final static String IP3 = "WL-Proxy-Client-IP";
	public final static String UNKNOWN = "unknown";
	public final static String COMMA = ",";
	public static void setCharacterEncoding(String encoding) throws UnsupportedEncodingException{		
		HttpServletRequest request = ServletActionContext.getRequest();
		request.setCharacterEncoding(encoding);
	}	
	
	public static String getParameter(String key){	
		HttpServletRequest request = ServletActionContext.getRequest();
		return request.getParameter(key);
	}
	
	public static void setAttribute(String key, Object value){	
		HttpServletRequest request = ServletActionContext.getRequest();
		request.setAttribute(key, value);
	}
	
	public static <T> T getParameter(String key, Class <T> type){
		HttpServletRequest request = ServletActionContext.getRequest();
		String value = request.getParameter(key);
		if(value!=null){
			if(Long.class.equals(type)){
				return (T)Long.valueOf(value);
			}else if(Integer.class.equals(type)){
				return (T)Integer.valueOf(value);
			}else{
				return (T)value;
			}
		}
		return null;
	}
	
	public static String getClientHost(){ //用户IPO
		HttpServletRequest request = ServletActionContext.getRequest();
		return request.getRemoteHost();
	}
	
	public static Cookie [] getCookies(){
		HttpServletRequest request = ServletActionContext.getRequest();
		Cookie [] cookies = request.getCookies();
		return cookies;
	}
	
	public static Cookie getCookie(String cookieName){
		Cookie [] cookies = getCookies();
		if(cookies!=null){
			for (int i = 0; i < cookies.length; i++) {
				Cookie cookie = cookies[i];
				if(cookieName.equals(cookie.getName())){
					return cookie;
				}
			}
		}
		return null;
	}
	
	public static String getCookieValue(String cookieName){
		Cookie cookie = getCookie(cookieName);
		if(cookie!=null){
			String cookieStr = cookie.getValue();
			if(cookieStr!=null){
				return EscapeUtil.unescape(cookieStr);
			}
		}
		return null;
	}
	public static Long getCookieMobileId(String cookieName){
		String mobileId = HttpHelp.getCookieValue(cookieName);
		if(!StringUtil.isEmpty(mobileId)){
			try{
				return  new Long(mobileId);
			}catch(Exception e){
				log.equals("home mothod error : Cann't  Convert Long [" + mobileId + "]");
				return  null;
			}
		}
		return null;
	}
	public static String getCookieMarketCode(String marketCode){
		return HttpHelp.getCookieValue(marketCode);
	}
	
	public static void addCookie(String domain, int maxAge, String path, String cookieName, String cookieValue){
		HttpServletResponse response = ServletActionContext.getResponse();
		Cookie cookie = new Cookie(cookieName, cookieValue);//用户ID 
		cookie.setPath(path);
		cookie.setMaxAge(maxAge);
		if(domain!=null){
			cookie.setDomain(domain);
		}
		response.addCookie(cookie);
	}
	

	public static void addJsonCookie(String domain, int maxAge, String path, String cookieName, String cookieValue)
	{
		HttpServletResponse response = ServletActionContext.getResponse();
		if(cookieValue!=null)
		{
			cookieValue=EscapeUtil.escape(cookieValue);
		}
		Cookie cookie = new Cookie(cookieName, cookieValue);//用户ID 
		cookie.setPath(path);
		cookie.setMaxAge(maxAge);
		if(domain!=null){
			cookie.setDomain(domain);
		}
		response.addCookie(cookie);
	}
	
	public static void removeCookie(String cookieName){
		HttpServletResponse response = ServletActionContext.getResponse();
		Cookie killMyCookie = new Cookie(cookieName, null); 
		killMyCookie.setMaxAge(0); 
		killMyCookie.setPath("/"); 
		response.addCookie(killMyCookie); 
	}
	

	
	public static <T> T getBean(ServletContext context, String beanName, Class <T> type){
		T bean = null;
		ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(context);
		if(ctx!=null){
			bean  = (T)ctx.getBean(beanName);
		}
		return bean;
	}
	public static String getIpd(){
		if (ServletActionContext.getRequest().getHeader("x-forwarded-for") == null) {
			return ServletActionContext.getRequest().getRemoteAddr();
	    }
			return ServletActionContext.getRequest().getHeader("x-forwarded-for");
	}
	public static String getIpAddr() {
		HttpServletRequest request=ServletActionContext.getRequest();
		String ip = request.getHeader(IP1);
		if (ip == null || ip.length() == 0|| UNKNOWN.equalsIgnoreCase(ip)) {
			ip = request.getHeader(IP2);
		}
		if (ip == null || ip.length() == 0|| UNKNOWN.equalsIgnoreCase(ip)) {
			ip = request.getHeader(IP3);
		}
		if (ip == null || ip.length() == 0|| UNKNOWN.equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		if (ip.contains(COMMA)) {
			int i = ip.indexOf(COMMA);
			ip = ip.substring(0, i);
		}
		return ip;
	}
	
	public static String  getURL() throws Exception{
		HttpServletRequest request = ServletActionContext.getRequest();
		Enumeration e=(Enumeration)request.getParameterNames();
		StringBuffer sbf=new StringBuffer();
		sbf.append(request.getRequestURI());
		sbf.append("?");
	    while(e.hasMoreElements())     {   
	       String  parName=(String)e.nextElement(); 
	       String value=request.getParameter(parName); 
	       sbf.append(parName);
	       sbf.append("=");
	       sbf.append(value);
	       sbf.append("-");//特意替换,如果用&表示,则会出问题.
	    }  
	    String url=sbf.toString();
	    return url=url.substring(0, url.length()-1);
	}
}
